package com.dhx.dao.impl;
import com.dhx.utils.*;
import com.dhx.dao.UserDao;
import com.dhx.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    @Override
    public Boolean queryUserById(String id) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from t_user where id= ?";
        PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
        ResultSet rs = null;
        try {
            ps.setString(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return false;
    }

    @Override
    public User queryUserById(String id, String password,String cate) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from t_user where id= ? and password= ? and cate=?";
        PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
        ResultSet rs = null;
        User user = null;
        System.out.println(conn);
        try {
            ps.setString(1, id);
            ps.setString(2, password);
            ps.setString(3,cate);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User(rs.getString("id"), rs.getString("username"), rs.getString("password"), rs.getString("cate"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public int saveUser(User user) {
        String sql = "insert into t_user values(?,?,?,?)";
        Object[] objs = {user.getId(), user.getUsername(), user.getPassword(), user.getCate()};
        int n = DBUtil.excuteDML(sql, objs);
        return n;
    }
}
